import React, { ReactNode, useState } from 'react';
import {
  Box,
  Container,
  CustomerMenu,
  HeroPortal,
  LoadingIcon,
  makeToast,
  Tabs,
} from '@nova-hf/ui';
import Layout from 'beta/components/layouts/Layout';
import { IContext } from 'beta/typings/context';
import { inject } from 'mobx-react';
import Link from 'next/link';
import { useRouter } from 'next/router';
import UI from 'store/ui';
import {
  BankClaimPaymentMethod,
  CreditCardPaymentMethod,
  PaymentTypeV2,
  useCustomerNameQuery,
  useDeletePaymentMethodMutation,
  usePaymentMethodsQuery,
} from 'typings/graphql';
import { formatCardExpiryDate } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';

import { ConfirmDeleteModal } from '../../components/ConfirmDeleteModal';
import { Hreyfingar } from '../containers/Hreyfingar';
import { Thjonustur } from '../containers/Thjonustur';

type StillingarProps = {
  ui: UI;
};

const Stillingar = ({ ui }: StillingarProps) => {
  const { t } = useTranslation('stillingar');
  const router = useRouter();
  const customerId: string = (router.query.customerId as string) ?? '';
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [deletePaymentMethod, { loading: loadingDelete }] = useDeletePaymentMethodMutation({});
  const { data, loading, error } = usePaymentMethodsQuery({
    variables: {
      input: {
        page: 1,
        perPage: 20,
        id: customerId,
      },
    },
  });

  const { data: customerData } = useCustomerNameQuery({
    variables: {
      input: {
        id: customerId,
      },
    },
  });

  if (!data?.paymentMethods || error || loading || loadingDelete) {
    return (
      <Box display="flex" alignItems="center" justifyContent="center">
        <LoadingIcon color="purple" size={80} />
      </Box>
    );
  }
  const COLOR = 'pink';
  const currentPaymentMethod = data?.paymentMethods?.paymentmethods?.find(
    (x) => x?.id === router.query.paymentMethodId,
  );

  const { expiry, issuer, type, maskedNumber, nick, id } =
    currentPaymentMethod as CreditCardPaymentMethod & BankClaimPaymentMethod;

  const title = nick ? nick : type ? type : '';
  const onDelete = async (id: string) => {
    try {
      const res = await deletePaymentMethod({
        variables: {
          input: {
            Id: id,
          },
        },
      });
      if (!res.data?.deletePaymentMethod?.message) {
        makeToast.danger(t('payment.paymentMethod.deletePaymentMethodFail'), '');
      } else {
        makeToast.success(t('payment.paymentMethod.deletePaymentMethodSuccess'), '');
      }
    } catch (error) {
      if (error instanceof Error)
        makeToast.danger(t('payment.paymentMethod.deletePaymentMethodFail'), error.message);
    }
    router.replace({ pathname: `/beta/${customerId}/stillingar`, query: { tab: 'greidslur' } });
  };
  return (
    <Layout hasCustomerMenu backgroundColor="white">
      <Container>
        <HeroPortal
          color={COLOR}
          title={
            type === PaymentTypeV2.BankClaim
              ? t('payment.paymentMethod.bankclaim')
              : maskedNumber?.slice(-8)
          }
        />
        <CustomerMenu
          title={title}
          subtitle={issuer || ''}
          button={{
            colorScheme: COLOR,
            text: t('payment.paymentMethod.deletePaymentMethod'),
            icon: 'close',
            onClick: () => setIsDeleteOpen(true),
          }}
          color={COLOR}
          icon="wallet"
          backButton={{
            renderAs: 'a',
            colorScheme: COLOR,
            text: 'Til baka',
            icon: 'longArrowLeft',
            wrapper: (link: ReactNode) => (
              <Link href={`/beta/${router.query.customerId}/stillingar`} passHref legacyBehavior>
                {link}
              </Link>
            ),
          }}
          extraInfo={[
            {
              leftList: {
                label: t('payment.paymentMethod.cardHolder'),
                list: [{ text: customerData?.customer?.name ?? '' }],
              },
              ...(type !== PaymentTypeV2.BankClaim && {
                rightList: {
                  label: t('payment.paymentMethod.cardNumber'),
                  list: [
                    {
                      text:
                        `${maskedNumber?.slice(-8)} ${formatCardExpiryDate(expiry ?? '')}` ?? '',
                    },
                  ],
                },
              }),
            },
          ]}
          mainButton={{
            renderAs: 'a',
            colorScheme: COLOR,
            text: t('service.help'),
            icon: 'chat',
            onClick: () => ui?.setIsContactMenuOpen(true),
          }}
        />
        <Container>
          <Box paddingX={8} marginBottom={12} width="100%" backgroundColor="white" maxWidth="100%">
            <Tabs
              tabBaseId="settings"
              tabBaseLabel="settings tabs"
              selectedTab="subscriptions"
              tabs={[
                {
                  id: 'subscriptions',
                  label: t('service.linkedSubscriptions'),
                  panelContent: <Thjonustur />,
                },
                {
                  id: 'hreyfingar',
                  label: t('service.movements'),
                  panelContent: <Hreyfingar />,
                },
              ]}
            />
          </Box>
        </Container>
        <ConfirmDeleteModal
          isLoading={loadingDelete}
          onDelete={() => onDelete(id)}
          onClose={() => setIsDeleteOpen(false)}
          isVisible={isDeleteOpen}
          onVisibilityChange={(isVisible) => setIsDeleteOpen(isVisible)}
        />
      </Container>
    </Layout>
  );
};

Stillingar.getInitialProps = ({ pathname, query }: IContext) => {
  return {
    pathname,
    customerId: query.customerId,
    namespacesRequired: ['stillingar'],
  };
};

export default inject('ui')(Stillingar);
